package controllers;

import indexing.KeywordIndex;

import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/*import util.pdf.PDF;*/

import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.JsonNode;
import org.elasticsearch.index.query.QueryBuilders;
import com.opentok.api.OpenTokSDK;
import com.opentok.exception.OpenTokException;
import com.opentok.api.constants.SessionProperties;
import com.avaje.ebean.TxType;
import com.github.cleverage.elasticsearch.IndexQuery;
import com.github.cleverage.elasticsearch.IndexResults;
import com.ning.http.client.Request;

import models.*;
import play.cache.Cache;
import play.data.DynamicForm;
import play.data.Form;
import play.db.ebean.Transactional;
import play.libs.F.Promise;
import play.libs.WS;
import play.mvc.*;
import play.mvc.BodyParser.Json;
import utils.MailerScheduler;
import utils.GCMSender.Data;
import views.html.*;
import scala.actors.threadpool.Arrays;
import securesocial.core.java.SecureSocial;
import securesocial.core.java.SocialUser;
import static play.libs.Json.toJson;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;

import plugins.S3Plugin;

public class Appment extends Controller{
	public static Result welcome() {
		System.out.println(request().getHeader(USER_AGENT));
	    return ok(welcome.render(request().getHeader(USER_AGENT)));
	  }

	public static Result loginMobile() {
	    return ok(loginmobile.render());	  		
	  }
	
	public static  class SendMessage {

		public String collapse_key="new_document";
		public int time_to_live=108;
		public boolean  delay_while_idle=true;
		public Data data= new Data();
		public List<String> registration_ids=new ArrayList<String>();
	}


	public static  class Template {

		public String topic;
		public int id;
	}
	@SecureSocial.Secured
	public static Result getTempalate(Long id) {
		DoctorsReferralTemplates doc = DoctorsReferralTemplates.getTemplateDetails(id);
		User user = User.getUserDetails(doc.doctor.id);
    	GetObjectRequest getObjectRequest = new GetObjectRequest("appment", user.userid+"/"+doc.S3fileName);
        S3Object s = S3Plugin.amazonS3.getObject(getObjectRequest);
		File f=new File(doc.fileName);
		try{
		IOUtils.copy(s.getObjectContent(), new FileOutputStream(f));
		}catch(Exception ex){
	    	ex.printStackTrace();
	    }
		//response().setContentType(arg0)
		return ok(f);
	}
	
	@SecureSocial.Secured
	public static Result postUserTemplate() {
		Form<Template> updateForm = form(Template.class).bindFromRequest();
	  	SocialUser sUser = SecureSocial.currentUser();
	  	User user = User.authenticate(sUser.id.provider,sUser.id.id);
	    Http.MultipartFormData body = request().body().asMultipartFormData();
        Http.MultipartFormData.FilePart uploadFilePart = body.getFile("upload");
        DoctorsReferralTemplates docTemplate = new DoctorsReferralTemplates();
        String S3FileName=UUID.randomUUID().toString();
        docTemplate.topicName= updateForm.get().topic;
        docTemplate.fileName=uploadFilePart.getFilename();
        docTemplate.S3fileName= S3FileName;
        docTemplate.fileType=uploadFilePart.getContentType();
        if(updateForm.get().id >0){
        	docTemplate.id = updateForm.get().id;	
        	docTemplate.update();
        }else{
        	docTemplate.doctor = new User();
        	docTemplate.doctor.id= user.id;
        	docTemplate.save();
        }
        
        if (uploadFilePart != null) {
        	PutObjectRequest putObjectRequest = new PutObjectRequest("appment", user.userid+"/"+S3FileName, uploadFilePart.getFile());
            putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead); // public for all
            S3Plugin.amazonS3.putObject(putObjectRequest);
           /* S3File s3File = new S3File();
            s3File.name = uploadFilePart.getFilename();
            s3File.file = uploadFilePart.getFile();
            s3File.save();*/
          //  return redirect(routes.Application.index());
        }
        else {
            //return badRequest("File upload error");
        }
	  	//List<DoctorsReferralTemplates> doctorTemplates = DoctorsReferralTemplates.getDoctorsTemplates(user.id); 
	  	return ok();
	  }
	
	public static class Data{
		public String message = "Hi";
	} 

	  //@SecureSocial.Secured  
	  public static Result sendNotification(){
/*		  SendMessage sm = new SendMessage();
		  sm.registration_ids.add("APA91bGFAZT_PFBdpK9DLglWHexrd74QUlDVEl2gtojlW4-MFGbCmbmt5KVxt98MYlkXytlO9beC6VZetKaBOJ_WZOKyhuTv7777rDkcoYhiQPwxc2EpY-Ds3499FBi73xipE2EalcTLho8SlXBPGe466Dy92f9wZQ");
		  String s = toJson(sm).toString();
		  Promise<WS.Response> result= WS.url("https://android.googleapis.com/gcm/send")
				  .setHeader("content-type","application/json")
		.setHeader("Authorization", "key=AIzaSyDXEeoqCDTNZn-IX3In1aPBvZBfns_zjzU")
		.post(s);
		  System.out.println("status is :"+result.get().getBody()+ " "+ result.get().getStatus());*/
		  AppointmentHistory appointment = new AppointmentHistory();
		  appointment.doctor = new User();
		  appointment.doctor.id = 9;
		  User user = new User();
		  MailerScheduler.sendGCMNotification(appointment,user,"New Appointment on ");
		    return ok();
		  
	  }
	  public static Result fetchAllHospitals(){
		  List<Hospitals> hospitals = Hospitals.getAllHospitals();
		  return ok(toJson(hospitals));
	  }
	  
	  
	  public static Result fetchAllLabs(){
		  List<Labs> labs = Labs.getAllLabs();
		  return ok(toJson(labs));
	  }

	  public static class LatLng{
		  public Double latitude;
		  public Double longitude;
		  public Long hospitalId;
		  public String speciality;
		  public String complaint;
		  public String city;
	  }
	  public static final double PI = 3.14159265;
	  public static final double deg2radians = PI/180.0;
	  
	  @SecureSocial.Secured
	  public static Result fetchHospitalList(){
		  Form<LatLng> getForm = form(LatLng.class).bindFromRequest();
		  Long hospitalId = getForm.get().hospitalId;
		  String speciality = getForm.get().speciality;
		  String city= getForm.get().city;
		  List<DoctorHospital> hospitalDetailsOfDoctor = DoctorHospital.getHospitalsWithDoctors(hospitalId,speciality,city);
		  List<Hospitals> hospitals = new ArrayList<Hospitals>();
		  List<Hospitals> hospitals1 = new ArrayList<Hospitals>();
		  Hospitals h1 = new Hospitals();
		  h1.speciality = new ArrayList<String>();
		  String hospitalName = "";
			  for(DoctorHospital h: hospitalDetailsOfDoctor){
				  if(hospitalName.equals(h.hospitals.hospitalName)){
					  System.out.println("sp:"+h.doctorDetails.specialities.speciality);
					  h1.speciality.add(h.doctorDetails.specialities.speciality);
				  }else{
					  if(!"".equals(hospitalName)){
						  hospitals1.add(h1);
					  }
					  h1= new Hospitals();
					  h1.speciality = new ArrayList<String>();
					  h1.speciality.add(h.doctorDetails.specialities.speciality);
					  hospitalName= h.hospitals.hospitalName;
					  h1.hospitalName =h.hospitals.hospitalName;
					  h1.hospitalAddress1=h.hospitals.hospitalAddress1;
					  h1.hospitalAddress2=h.hospitals.hospitalAddress2;
					  h1.hospitalCity=h.hospitals.hospitalCity;
					  h1.hospitalState=h.hospitals.hospitalState;
					  h1.hospitalContactNo=h.hospitals.hospitalContactNo;
					  h1.hospitalZip=h.hospitals.hospitalZip;
					  h1.latitude=h.hospitals.latitude;
					  h1.longitude= h.hospitals.longitude;
				  }
				    
			  }
			  hospitals1.add(h1);
		  //HashSet<Hospitals> uniqueValues = new HashSet(hospitals1);
		  hospitals.addAll(hospitals1);
	  
		  double lat2,lon2;
		  double lat1=getForm.get().latitude;
		  double lon1=getForm.get().longitude;
		  for(int i=0;i<hospitals.size();i++){
			  for(int j=0;j <hospitals.size();j++){
				  lat2 = hospitals.get(i).latitude;
				  lon2 = hospitals.get(i).longitude;
				  hospitals.get(i).distance=
						 ( 2*Math.asin(Math.sqrt(Math.pow(Math.sin((lat1-lat2)/2),2.0) +
		                  Math.cos(lat1)*Math.cos(lat2)*Math.pow(Math.sin((lon1-lon2)/2)
		                		  	,2.0))))*100;
				  
			  }
		  }
		  return ok(toJson(hospitals));
	  }
	public static class SendComment {

		public String name;
		public String email;
		public String  subject;
		public String comments;
	}

	public static Result sendComments() {
		Form<SendComment> updateForm = form(SendComment.class).bindFromRequest();
		String[] appment = {"appment@gmail.com"};
		MailerScheduler.scheduleMail(appment, updateForm.get().subject+": from "+updateForm.get().name, "Hi,<br>"+updateForm.get().name+" with emailid: "+updateForm.get().email+" has sent this note.<br>"+updateForm.get().comments);
	    return ok();
	  }
	
	public static class CustomProfile {

		public String profileName;
		public List<Long> examIds = new ArrayList<Long>();
	}
	
	@Transactional
	@SecureSocial.Secured
	public static Result saveCustomProfile() {
		Form<CustomProfile> updateForm = form(CustomProfile.class).bindFromRequest();
		SocialUser sUser = SecureSocial.currentUser();
    	User user = User.authenticate(sUser.id.provider,sUser.id.id);  
		ExaminationProfiles ex = new ExaminationProfiles();
		List<Long> examIds = updateForm.get().examIds;
		 List<Long> profiles = ExaminationProfiles.getExamsForDoc(user.id,updateForm.get().profileName);
		 List<Long> newProfiles = new ArrayList<Long>();
		for(Long l: examIds){
			if(!profiles.contains(l)){
				ex.profileName =updateForm.get().profileName;
				ex.examination= new Examination();
				ex.examination.id=l;
				ex.updatedBy= new User();
				ex.updatedBy.id=user.id;
				ex.save();
				ex = new ExaminationProfiles();
			}
			newProfiles.add(l);
			
		}
		for(Long l : profiles ){
			if(!newProfiles.contains(l)){
				ex.id=l;
				ex.delete();
			}
		}
	    return ok();
	  }
	

	@SecureSocial.Secured
	public static Result checkUserDetails() {
		SocialUser sUser = SecureSocial.currentUser();
    	User user = User.authenticate(sUser.id.provider,sUser.id.id);  
    	HashMap<String, Object> data = new HashMap<String, Object>();
    	if(null == user){
    		user = new User();
    		user.email =sUser.email;
    	}
    	data.put("user",user);
    	if(null != user &&"D".equals(user.userType)){
        	List<Hospitals> hospitals = Hospitals.getAllHospitals();
        	data.put("hospitals",hospitals);
        	List<DoctorHospital> hospitalDetailsOfDoctor = DoctorHospital.getHospitalsForDoctor(user.id);
        	data.put("myhospitals",hospitalDetailsOfDoctor);
        	DoctorDetails doctordetails = DoctorDetails.getDoctorDetails(user.id);
        	data.put("doctordetails",doctordetails);
        	
    	}
	    return ok(toJson(data));
	  }
	
	   public  static class Registration{
	    	public String registrationId ; 
	    }

		@Transactional
		@SecureSocial.Secured
		public static Result updateGCM() {
			Form<Registration> updateForm = form(Registration.class).bindFromRequest();
			SocialUser sUser = SecureSocial.currentUser();
			User user = User.authenticate(sUser.id.provider,sUser.id.id);
			User updateUser = new User();	
			updateUser.id= user.id;
			updateUser.gcmRegistrationId= updateForm.get().registrationId;
			updateUser.update();	
		    return ok();
		  }
	
	public static class PersonalDetails {

		public String emailid;
		public String phonenumber;
		public String  userType;
		public String clientId;
		public String registrationNo;
		public String speciality;
		public String name;
		public Long labId;
		public List<Long> hospitals=new ArrayList<Long>();
	}

	@Transactional
	@SecureSocial.Secured
	public static Result updateUserDetails() {
		Form<PersonalDetails> updateForm = form(PersonalDetails.class).bindFromRequest();
		SocialUser sUser = SecureSocial.currentUser();
		User user = User.authenticate(sUser.id.provider,sUser.id.id);
		User updateUser = new User();
		DoctorDetails doctor = new DoctorDetails();
		if(null == user){
			User dummyUser = null;
			updateUser.provider= sUser.id.provider;
			updateUser.name=updateForm.get().name;
			updateUser.userid = sUser.id.id;
			updateUser.userType=updateForm.get().userType;
			if(null != updateForm.get().clientId){
				updateUser.clientId = updateForm.get().clientId;
			}
			if(null != updateForm.get().emailid){
				updateUser.email=updateForm.get().emailid;
			}else{
				updateUser.email=sUser.email;
			}
			dummyUser= User.checkDummyUser(updateUser.email);			
			updateUser.phoneNumber=updateForm.get().phonenumber;
			updateUser.name = sUser.displayName;
			if(dummyUser !=null){
				updateUser.id= dummyUser.id;
				updateUser.update();
			}else{
				updateUser.save();	
			}
			
			if("D".equals(updateUser.userType)){
				doctor.doctor = new User();
				doctor.doctor.id = updateUser.id;
				doctor.registrationNo= updateForm.get().registrationNo;
				Specialities speciality = Specialities.getSpecialityByName(updateForm.get().speciality);
				doctor.specialities = new Specialities();
				doctor.specialities.id= speciality.id;
				doctor.save();
				if(updateForm.get().hospitals.size()>0){
					DoctorDetails doc = DoctorDetails.getDoctorDetails(updateUser.id);
					DoctorHospital docHospital = new DoctorHospital();

					for(Long l: updateForm.get().hospitals){
						docHospital.doctorDetails = doc;
						docHospital.hospitals= new Hospitals();
						docHospital.hospitals.id = l;
						docHospital.save();
						docHospital = new DoctorHospital();
					}
				}
				
			}else if("L".equals(updateUser.userType)){
				LabDetails lab = new LabDetails();
				lab.labs= new Labs();
				lab.technician = new User();
				lab.technician.id=updateUser.id;
				lab.labs.id = updateForm.get().labId;
				lab.save();
			}
		}else{
			updateUser.id= user.id;
			updateUser.email = updateForm.get().emailid!=null ?updateForm.get().emailid:null;
			updateUser.phoneNumber=updateForm.get().phonenumber != null? updateForm.get().phonenumber:null;
			updateUser.clientId=updateForm.get().clientId!=null?updateForm.get().clientId:null;
			if(updateUser.email !=null ||updateUser.phoneNumber!=null || updateUser.clientId !=null){
				updateUser.update();	
			}
			
			if("D".equals(user.userType)){
				doctor = DoctorDetails.getDoctorDetails(updateUser.id);
				doctor.registrationNo= updateForm.get().registrationNo!=null ? updateForm.get().registrationNo:null;
				if(updateForm.get().speciality!=null){
					Specialities speciality = Specialities.getSpecialityByName(updateForm.get().speciality);
					doctor.specialities = new Specialities();
					doctor.specialities.id= speciality.id;
				}
				if(updateForm.get().speciality!=null || updateForm.get().registrationNo!=null){
					doctor.update();	
				}
				if(updateForm.get().hospitals.size()>0){
					DoctorDetails doc = DoctorDetails.getDoctorDetails(updateUser.id);
					DoctorHospital docHospital = new DoctorHospital();
					List<DoctorHospital> existingHospitals = DoctorHospital.getHospitalsForDoctor(updateUser.id);
					boolean found = false;					
					for(Long l: updateForm.get().hospitals){
						for(DoctorHospital d: existingHospitals ){
							if(d.hospitals.id == l){
								found=true;
							}
						}
						if(!found){
							docHospital.doctorDetails = doc;
							docHospital.hospitals= new Hospitals();
							docHospital.hospitals.id = l;
							docHospital.save();
							docHospital = new DoctorHospital();
							
						}
						found=false;
					}
//					List<Long> hospitalIds = new ArrayList<Long>();
					for(DoctorHospital d: existingHospitals ){
						if(!updateForm.get().hospitals.contains(d.id)){
							docHospital = new DoctorHospital();
							docHospital.id = d.id;
							docHospital.hospitals= new Hospitals();
							docHospital.hospitals.id=d.hospitals.id;
							docHospital.doctorDetails= new DoctorDetails();
							docHospital.doctorDetails.id=d.doctorDetails.id;
							DoctorSchedule.deleteSchedule(d.doctorDetails.id, d.hospitals.id);
//							hospitalIds.add(d.hospitals.id);
//							docHospital.delete();
						}
						
					}


				}

			}

		}
	    return ok();
	  }
	
	public static class AddAppointment {

		public Long doctorId;
		public Long appointmentId;
		public String appointmentdate;
		public String appointmenttime;
		public String complaint;
		public String otherdetails;
		public String videoconf;
		public Long selectProblemTemplate;
	}

	@Transactional
	@SecureSocial.Secured  
	  public static Result saveAppointment(){
			Form<AddAppointment> appointmentForm = form(AddAppointment.class).bindFromRequest();
		  	SocialUser sUser = SecureSocial.currentUser();
			User user = User.authenticate(sUser.id.provider,sUser.id.id);
		  	AppointmentHistory appointment = new AppointmentHistory();
		  	appointment.patient= new User();
		  	appointment.patient.id = user.id;
		  	appointment.appointmentComment=appointmentForm.get().otherdetails;
		  	appointment.doctor= new User();
		  	appointment.doctor.id=appointmentForm.get().doctorId;
		  	if(appointmentForm.get().complaint !=null){
		  		appointment.appointmentHeadline=appointmentForm.get().complaint;	
		  	}
		  	
		  	if(appointmentForm.get().selectProblemTemplate !=null && appointmentForm.get().selectProblemTemplate >0){
		  		appointment.problem = new DoctorsReferralTemplates();
		  		appointment.problem.id =appointmentForm.get().selectProblemTemplate;	
		  	}
		  	
		  	appointment.video =appointmentForm.get().videoconf;
		    try{
			  	SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
			  	Date d = df.parse(appointmentForm.get().appointmentdate); 
			  	appointment.dateOfAppointment = d;
			    DateFormat TWELVE_TF = new SimpleDateFormat("hh:mm a");
			    DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm");		    	
			    appointment.appointmentTime =TWENTY_FOUR_TF.format(TWELVE_TF.parse(appointmentForm.get().appointmenttime));
			    if(appointmentForm.get().appointmentId >0){
			    	appointment.id= appointmentForm.get().appointmentId;
			    	appointment.update();
			    }else{
			    	appointment.save();	
			    }
			    
			    MailerScheduler.newAppointment(appointment,user);
			    DateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yyyy");
			    User duser = User.getUserDetails(appointment.doctor.id);
			    MailerScheduler.sendGCMNotification(appointment,duser,"New Appointment on "+dateFormat.format(d));
		    }catch(Exception ex){
		    	ex.printStackTrace();
		    }

		    return ok();
		  
	  }


	@Transactional
	@BodyParser.Of(BodyParser.Json.class)
	@SecureSocial.Secured  
	  public static Result saveTests(){
		int size = request().body().asJson().size();
		Tests t = new Tests();
		for(int i=0;i < size;i++ ){
			JsonNode j = request().body().asJson().get(i);
			t.id= j.findPath("test").getLongValue();
			t.testResult=j.findPath("reading").getTextValue();
			t.update();
			t = new Tests();
		}	
		return ok();
	}
	
	public static class SavePrescriptions {

		public List<Long> tests;
		public Long appointmentId;
		public String appointmentDoctorComment;
		public Long lab;
	}

	@Transactional
	@SecureSocial.Secured  
	  public static Result savePrescriptions(){
			Form<SavePrescriptions> testsForm = form(SavePrescriptions.class).bindFromRequest();
			Tests test = new Tests();
			Long appointmentId = testsForm.get().appointmentId;
			//test.delete();
			int s = Tests.deleteTests(appointmentId);
			List<Long> tests = testsForm.get().tests;
			for(Long eachtest: tests){
				test = new Tests();
				test.appointment = new AppointmentHistory();
				test.examination= new Examination();
				test.appointment.id= appointmentId;
				test.examination.id = eachtest.longValue();
				test.save();
			}
			AppointmentHistory appointmentHistory = new AppointmentHistory();
			appointmentHistory.id= appointmentId;
			appointmentHistory.doctorComments= testsForm.get().appointmentDoctorComment;
			appointmentHistory.attended = "Y";
			appointmentHistory.labId=testsForm.get().lab;
			appointmentHistory.update();
		    return ok();
		  
	  }

	@SecureSocial.Secured
	public static Result appment() {
		SocialUser sUser = SecureSocial.currentUser();
    	User user = User.authenticate(sUser.id.provider,sUser.id.id);

	    return ok(appment.render(sUser,user));
	  }
	
	@SecureSocial.Secured
	public static Result getUserDetails() {
		SocialUser sUser = SecureSocial.currentUser();
    	User user = User.authenticate(sUser.id.provider,sUser.id.id);
    	HashMap<String, Object> data = new HashMap<String, Object>();
    	sUser.oAuth1Info=null;
    	data.put("social",sUser);
    	data.put("appment",user);
	    return ok(toJson(data));
	  }

	
	public static class FindDoctor {

		public String name;
		public String email;
	}

	@SecureSocial.Secured
	public static Result getMatchingDoctorNames(){
		Form<FindDoctor> details= form(FindDoctor.class).bindFromRequest();

		List<DoctorHospital> users = DoctorHospital.getMatchingDoctorNames(details.get().name+" ",details.get().email);
		return ok(toJson(users));
	}
	  @SecureSocial.Secured  
	  public static Result getFeed(){
		  	SocialUser sUser = SecureSocial.currentUser();
	    	User user = User.authenticate(sUser.id.provider,sUser.id.id);
	    	LabDetails lab = new LabDetails();
	    	long labid="L".equals(user.userType)?lab.getLabDetails(user.id).labs.id:0;
	    	List<AppointmentHistory> appointments = AppointmentHistory.getAppointmentDetailsForFeed(user.id,user.userType,labid);
		    return ok(toJson(appointments));
		  
	  }

	  @SecureSocial.Secured  
	  public static Result getDoctorEarnings(){
		  	SocialUser sUser = SecureSocial.currentUser();
	    	User user = User.authenticate(sUser.id.provider,sUser.id.id);
	    	List<DoctorEarning> appointments = AppointmentHistory.getDoctorEarning(user.id);
			HashMap<String, Object> data = new HashMap<String, Object>();
			data.put("earnings", appointments);
		    return ok(toJson(data));
		  
	  }
	  
	  @SecureSocial.Secured  
	  public static Result getSchedule(){
		  	SocialUser sUser = SecureSocial.currentUser();
	    	User user = User.authenticate(sUser.id.provider,sUser.id.id);
	    	List<DoctorSchedule> schedule = DoctorSchedule.getSchedule(user.id);
		    return ok(toJson(schedule));
		  
	  }
	  
	  @SecureSocial.Secured  
	  public static Result getScheduleAtHospital(Long hospitalId){
		  	SocialUser sUser = SecureSocial.currentUser();
	    	User user = User.authenticate(sUser.id.provider,sUser.id.id);
	    	List<DoctorSchedule> schedule = DoctorSchedule.getScheduleAtHospital(user.id, hospitalId);
		    return ok(toJson(schedule));
		  
	  }
	  

		public static class Schedule {

			public Long id;
			public Long day;
			public Long iddoctor_detail;
			public String startTime;
			public String endTime;
		}


		@Transactional
		@BodyParser.Of(BodyParser.Json.class)
		@SecureSocial.Secured  
		  public static Result saveSchedule(){
				int size = request().body().asJson().size();
				DoctorSchedule doctorSchedule = new DoctorSchedule();
				SocialUser sUser = SecureSocial.currentUser();
		    	User user = User.authenticate(sUser.id.provider,sUser.id.id);  
		    	DoctorDetails doctorDetails = DoctorDetails.getDoctorDetails(user.id);
//				int state = DoctorSchedule.deleteSchedule(doctorDetails.id);
		    	List<Long> scheduleIds = new ArrayList<Long>();
		    	List<Long> scheduleIdsToDelete = new ArrayList<Long>();
		    	long hospitalId=request().body().asJson().get(0).findPath("hospitalId").getIntValue();
		    	List<DoctorSchedule> currentSchedule = DoctorSchedule.getScheduleAtHospital(user.id, hospitalId);
				for(int i=0;i < size;i++ ){
					JsonNode j = request().body().asJson().get(i);
					doctorSchedule.hospitals = new DoctorHospital();
					if(j.findPath("hospitalId").getIntValue()==0 && j.findPath("id").getIntValue() >0){
						doctorSchedule.hospitals.id = j.findPath("hospitals").findPath("id").getIntValue();	
					}else{
						doctorSchedule.hospitals.id = j.findPath("hospitalId").getIntValue();
					}
					
					doctorSchedule.id = j.findPath("id").getIntValue();
					doctorSchedule.day = j.findPath("day").getIntValue();
					doctorSchedule.startTime=j.findPath("startTime").getTextValue();
					doctorSchedule.endTime=j.findPath("endTime").getTextValue();
					doctorSchedule.doctorDetails= new DoctorDetails();					
					doctorSchedule.doctorDetails.id=doctorDetails.id;
					if(doctorSchedule.id >0){
						doctorSchedule.update();
						scheduleIds.add(doctorSchedule.id);
					}else{
						DoctorSchedule.addSchedule(doctorSchedule);
					}
					doctorSchedule = new DoctorSchedule();
					doctorSchedule.hospitals = new DoctorHospital();	
				}
				if(currentSchedule.size()>0){
					for(DoctorSchedule s: currentSchedule){
						if(!scheduleIds.contains(s.id)){
							scheduleIdsToDelete.add(s.id);
						}
					}
					if(scheduleIdsToDelete.size()>0){
						DoctorSchedule.deleteSchedules(doctorDetails.id,hospitalId,scheduleIdsToDelete);
					}
				}
				
			    return ok(toJson("success"));
			  
		  }

		@Transactional
		@BodyParser.Of(BodyParser.Json.class)
		@SecureSocial.Secured  
		  public static Result saveUnattended(){
				int size = request().body().asJson().size();
				AppointmentHistory appointment = new AppointmentHistory();
				SocialUser sUser = SecureSocial.currentUser();
		    	User user = User.authenticate(sUser.id.provider,sUser.id.id);  
				for(int i=0;i < size;i++ ){
					JsonNode j = request().body().asJson().get(i);
					appointment.amountPaid = j.findPath("amountPaid").getDoubleValue();
					if(null != appointment.amountPaid && appointment.amountPaid > 0){
						appointment.id = j.findPath("id").getLongValue();
						appointment.appointmentDuration =null;
						appointment.paymentStatus="Y";
						appointment.update();
						appointment = new AppointmentHistory();
					}
				}
			    return ok(toJson("success"));
			  
		  }
		
		@Transactional
		@BodyParser.Of(BodyParser.Json.class)
		@SecureSocial.Secured  
		  public static Result saveUserStatus(){
				int size = request().body().asJson().size();
				User user = new User();
				for(int i=0;i < size;i++ ){
					JsonNode j = request().body().asJson().get(i);
					user.approved = j.findPath("approved").getTextValue();
					if(null != user.approved && "Y".equals(user.approved) ){
						user.id = j.findPath("doctor").findPath("id").getLongValue();
						user.update();
						user = new User();
					}
				}
			    return ok(toJson("success"));
			  
		  }
		
		
	  @SecureSocial.Secured  
	  public static Result getAppointmentDetails(Long id){
		  	AppointmentHistory appointment = AppointmentHistory.getAppointmentDetails(id.longValue());
		    return ok(toJson(appointment));
		  
	  }
	  
	  @SecureSocial.Secured  
	  public static Result getMonthEarnings(Long id){
		  	SocialUser sUser = SecureSocial.currentUser();
	    	User user = User.authenticate(sUser.id.provider,sUser.id.id);
		  	List<AppointmentHistory> appointment = AppointmentHistory.getMonthEarnings(user.id,id.longValue());
		    return ok(toJson(appointment));
		  
	  }
	  
	  @SecureSocial.Secured  
	  public static Result getDoctorsAppointmentDetails(Long id){
		  	List<Tests> tests = Tests.getTests(id.longValue());
			HashMap<String, Object> data = new HashMap<String, Object>();
			data.put("examinations", tests);
		    return ok(toJson(data));
		  
	  }
	  
	  @SecureSocial.Secured  
	  public static Result getDoctorScheduleDay(Long doctorId, Long day, Long hospitalId){
		  	List<DoctorSchedule> doctorSchedule = DoctorSchedule.getDoctorScheduleDay(doctorId, day,hospitalId);
		    return ok(toJson(doctorSchedule));
		  
	  }

	  @SecureSocial.Secured  
	  public static Result getDoctorSchedule(Long doctorId){
		  List<DoctorSchedule> schedule = DoctorSchedule.getSchedule(doctorId);
		    return ok(toJson(schedule));
		  
	  }

	  @SecureSocial.Secured  
	  public static Result getDoctorSchedule4Mobile(Long doctorId, Long hospitalId){
		  List<DoctorSchedule> schedule = DoctorSchedule.getSchedule4Mobile(doctorId,hospitalId);
		    return ok(toJson(schedule));
		  
	  }

	  @SecureSocial.Secured  
	  public static Result getGraphs(){
		  	List<AdminGraph> amounts = AdminGraph.getDepartmentMonth();
		  	List<AdminGraph> yearamounts = AdminGraph.getYearlyRevenue();
		  	HashMap<String, Object> data = new HashMap<String, Object>();
		  	data.put("current", amounts);
		//  	data.put("years", yearamounts);
		    return ok(toJson(data));
		  
	  }
	  @SecureSocial.Secured  
	  public static Result getExistingDoctors(){
		  	SocialUser sUser = SecureSocial.currentUser();
		  	User user = User.authenticate(sUser.id.provider,sUser.id.id);
	    	List<String> doctors = AppointmentHistory.getExistingDoctors(user.id);
		    return ok(toJson(doctors));
		  
	  }

	  
	  @SecureSocial.Secured  
	  public static Result getKeyword(String query){
		    IndexQuery<KeywordIndex> keywordQuery = KeywordIndex.find.query();
	        keywordQuery.setBuilder(QueryBuilders.queryString(query));
	        IndexResults<KeywordIndex> keywordResults = KeywordIndex.find.search(keywordQuery);
	        List<KeywordIndex> keywords = keywordResults.results;
	        List<String> keyList=new ArrayList<String>();
	        for(KeywordIndex keyword:keywords){
	        	keyList.add(keyword.keywords);
	        }
		    return ok(toJson(keyList));
		  
	  }
	  
	  @SecureSocial.Secured  
	  public static Result getKeyWordSpeciality(String query){
		    return ok(toJson(Specialities.getSpecialityByKeyword(query).speciality));
		  
	  }
	  
	  @SecureSocial.Secured  
	  public static Result getDoctorName(String query,String speciality){
		  return ok(toJson(DoctorDetails.getDoctorName(query, speciality)));
		  
	  }

	  @SecureSocial.Secured  
	  public static Result getPatientDetails(String name,String clientId){
		  return ok(toJson(User.getPatientDetails(name, clientId)));
		  
	  }

	  
	  @SecureSocial.Secured  
	  public static Result getSpeciality(String query,String keyword){
		  List<Specialities> specialityDetails = Specialities.getSpecialities(query, keyword);
	    return ok(toJson(specialityDetails));
		  
	  }

	  
	  @SecureSocial.Secured  
	  public static Result getExaminations(){
		  List<Examination> examinations = Examination.getExaminations();
		  SocialUser sUser = SecureSocial.currentUser();
		  User user = User.authenticate(sUser.id.provider,sUser.id.id);
		  List<ExaminationProfiles> profiles = ExaminationProfiles.getProfiles(user.id);
		  List<String> examinationSubtypes = Examination.getDistinctExaminations();
		  List<String> distinctProfiles = ExaminationProfiles.getDistinctProfiles(user.id);
		  List<Labs> labs = Labs.getAllLabs();
		  HashMap<String, Object> data = new HashMap<String, Object>();
		  data.put("examinations", examinations);
		  data.put("profiles", profiles);
		  data.put("subtype", examinationSubtypes);
		  data.put("dprofiles", distinctProfiles);
		  data.put("labs", labs);
	    return ok(toJson(data));
		  
	  }

	  @SecureSocial.Secured  
	  public static Result getExaminationList(){
		  List<Examination> examinations = Examination.getExaminationList();		
	    return ok(toJson(examinations));
		  
	  }
	  @SecureSocial.Secured  
	  public static Result getProfilesForDoc(String term){
		  SocialUser sUser = SecureSocial.currentUser();
		  User user = User.authenticate(sUser.id.provider,sUser.id.id);
		  List<ExaminationProfiles> profiles = ExaminationProfiles.getProfilesForDoc(user.id,term);
	    return ok(toJson(profiles));
		  
	  }
	  
	  @SecureSocial.Secured  
	  public static Result getPatientName(String term){
		  List<User> patients = User.getPatients(term);
	    return ok(toJson(patients));
		  
	  }
	  
	  @SecureSocial.Secured  
	  public static Result getAllDoctors(){
		  List<User> doctors = User.getAllDoctors();
	    return ok(toJson(doctors));
		  
	  }
	  
	  @SecureSocial.Secured  
	  public static Result getProfilesForDocSearch(String term){
		  SocialUser sUser = SecureSocial.currentUser();
		  User user = User.authenticate(sUser.id.provider,sUser.id.id);
		  List<ExaminationProfiles> profiles = ExaminationProfiles.getProfilesForDocSearch(user.id,term);
	    return ok(toJson(profiles));
		  
	  }
		public static class SearchCriteria {

			public String complaint;
			public String speciality="";
			public String doctorname="";
			public String followupdoctorname="";
			public String datepicker;
			public Long hospital=new Long(0);
			public String city="";
			
		}

		@Transactional
		@SecureSocial.Secured
		public static Result getSearchResults() throws ParseException{
			Form<SearchCriteria> searchForm = form(SearchCriteria.class).bindFromRequest();
			Integer day = 0;
			if(null != searchForm.get().datepicker && !"".equals(searchForm.get().datepicker)){
				DateFormat formatter= new SimpleDateFormat("MM/dd/yyyy");
				Date dateOfAppointment= formatter.parse(searchForm.get().datepicker);
				DateFormat dayFormatter= new SimpleDateFormat("E");
				day=new Integer(checkDay( dayFormatter.format(dateOfAppointment)));
				
			}
			String doctorName;
			if(!"".equals(searchForm.get().followupdoctorname)){
				doctorName= searchForm.get().followupdoctorname;
			}else{
				doctorName=searchForm.get().doctorname;
			}
			List<String> specialities = new ArrayList<String>();
			if(null != searchForm.get().complaint){
				List<Specialities> specialityDetails = Specialities.getSpecialities(null, searchForm.get().complaint);
				for(Specialities s:specialityDetails){
					specialities.add(s.speciality);
				}
			}else if(!"".equals(searchForm.get().speciality)){
				specialities.add(searchForm.get().speciality);
			}
			List<DoctorSchedule> doctors= DoctorSchedule.getDoctors(specialities, doctorName, day,
					searchForm.get().hospital,searchForm.get().city);
			List<Schedules> schedules = new ArrayList<Schedules>();
			List<DoctorSchedule> docSchedules = new ArrayList<DoctorSchedule>();
			DoctorSchedule docSchedule = new DoctorSchedule();
			Schedules schedule = new Schedules();
			String name = "";
			for(DoctorSchedule sch : doctors){
				if(!sch.doctorDetails.doctor.name.equals(name)){
					System.out.println("t:"+name+" "+docSchedules.size());
					if(docSchedules.size()>0){
						schedule.sch= docSchedules;
						schedules.add(schedule);
					}
					docSchedules = new ArrayList<DoctorSchedule>();
					schedule = new Schedules();
					schedule.doc=sch.hospitals;
					name = sch.doctorDetails.doctor.name;
					
				}
				docSchedule.startTime= sch.startTime;
				docSchedule.endTime= sch.endTime;
				docSchedule.day= sch.day;
				docSchedules.add(docSchedule);
				docSchedule= new DoctorSchedule();
			}
			schedule.sch= docSchedules;
			schedules.add(schedule);

		    return ok(toJson(schedules));
		  }
		
		@SecureSocial.Secured
		public static Result getUnattended() {
			List<AppointmentHistory> appointments= AppointmentHistory.getUnattended();
		    return ok(toJson(appointments));
		  }

		@SecureSocial.Secured
		public static Result getUnapprovedUsers() {
			List<DoctorDetails> users= DoctorDetails.getUnapprovedUsers();
		    return ok(toJson(users));
		  }
		
		@SecureSocial.Secured
		public static Result getHistoryResults(Long id) {
			List<AppointmentHistory> appointments= AppointmentHistory.getAppointmentDetailsForFeed(id, "P",0);
		    return ok(toJson(appointments));
		  }
		
		@SecureSocial.Secured
		public static Result generatePrognosis(Long id) {
		  	List<Tests> tests = Tests.getTests(id);
		  	AppointmentHistory appointment = AppointmentHistory.getAppointmentDetails(id);
		  	DoctorDetails doctorDetail = DoctorDetails.getDoctorDetails(appointment.doctor.id);
			HashMap<String, Object> data = new HashMap<String, Object>();
			data.put("examinations", tests);
			data.put("appointment", tests);
			 return null /*PDF.ok(generatePrognosis.render(appointment, tests, doctorDetail))*/;

		  }

		@SecureSocial.Secured
		public static Result patientHistory(Long id) {
			if(id ==0){
			  	SocialUser sUser = SecureSocial.currentUser();
			  	User user = User.authenticate(sUser.id.provider,sUser.id.id);
			  	id=user.id;
			}
		  	PatientHistory history = PatientHistory.getPatientHistory(id);
		  	return null == history?ok():ok(toJson(history));

		  }

		@SecureSocial.Secured
		public static Result savePatientHistory() {
			Form<PatientHistory> historyForm = form(PatientHistory.class).bindFromRequest();
		  	SocialUser sUser = SecureSocial.currentUser();
		  	User user = User.authenticate(sUser.id.provider,sUser.id.id);
		  	if(historyForm.get().patient !=null){
		  		historyForm.get().patient.id=user.id;	
		  	}else{
		  		historyForm.get().patient = new User();
		  		historyForm.get().patient.id=user.id;
		  	}
		  	System.out.println("Id is:"+historyForm.get().patient.id);
		  	if(historyForm.get().id == null ||historyForm.get().id ==0 ){
		  		historyForm.get().save();
		  	}else{
		  		historyForm.get().update();
		  	}
		  		
		  	return ok();

		  }


		public static class RequestAppointment {

			public String date;
			public String requesttime;
			public String  comments;
		}

		@SecureSocial.Secured
		public static Result requestAppointment() {
			Form<RequestAppointment> updateForm = form(RequestAppointment.class).bindFromRequest();
		  	SocialUser sUser = SecureSocial.currentUser();
		  	User user = User.authenticate(sUser.id.provider,sUser.id.id);
			String[] appment = {"appment@gmail.com"};
			MailerScheduler.scheduleMail(appment, "Urgent: Appointment requested by " + user.name, "Hi,<br> My client Id is "+user.clientId+ " want an appointment on "+ updateForm.get().date + " at "+updateForm.get().requesttime+ ".<br>"+updateForm.get().comments+ "<br>This request is due to personal urgency. Kindly accomodate.<br>Thanks,<br>"+user.name);
		    return ok();
		  }

		@SecureSocial.Secured
		public static Result getUserTemplates() {
			Form<RequestAppointment> updateForm = form(RequestAppointment.class).bindFromRequest();
		  	SocialUser sUser = SecureSocial.currentUser();
		  	User user = User.authenticate(sUser.id.provider,sUser.id.id);
		  	List<DoctorsReferralTemplates> doctorTemplates = DoctorsReferralTemplates.getDoctorsTemplates(user.id); 
		  	return null == doctorTemplates ?ok():ok(toJson(doctorTemplates));
		  }

		
		
		public static class ReferPatient {

			public Long patientId;
			public String patientName;
			public String  patientPhone;
			public String  patientEmail;
			public Long referredDoctorId;
			public Long  referredDoctorHospitalId;
			public Long  referredForProblem;
			public String referredProblemDesc;
			public String  comments;
		}
		
		@SecureSocial.Secured
		public static Result referPatient() {
			Form<ReferPatient> updateForm = form(ReferPatient.class).bindFromRequest();
		  	SocialUser sUser = SecureSocial.currentUser();
		  	User user = User.authenticate(sUser.id.provider,sUser.id.id);
		  	AppointmentHistory apt = new AppointmentHistory();
	  		apt.doctor = new User();
	  		apt.doctor.id = updateForm.get().referredDoctorId;
	  		apt.referringDoctor = new User();
	  		apt.referringDoctor.id = user.id;

		  	if(updateForm.get().referredDoctorHospitalId !=null && updateForm.get().referredDoctorHospitalId >0){
		  		apt.hospital = new Hospitals();
		  		apt.hospital.id = updateForm.get().referredDoctorHospitalId;
		  	}
	  		
		  	if(updateForm.get().referredForProblem !=null && updateForm.get().referredForProblem >0){
		  		apt.problem = new DoctorsReferralTemplates();
		  		apt.problem.id = updateForm.get().referredForProblem;
		  		apt.problem.topicName = updateForm.get().referredProblemDesc;
		  	}
		  	apt.doctorComments = updateForm.get().comments;
	  		apt.patient = new User();
	  		boolean isNewUser = false;
		  	if(updateForm.get().patientId !=null && updateForm.get().patientId >0){
		  		apt.patient.id =updateForm.get().patientId; 
		  	}else{
		  		User patientDetails = User.authenticate("dummy",updateForm.get().patientEmail);
		  		User newUser = new User();
		  		newUser.name = updateForm.get().patientName;
		  		newUser.email= updateForm.get().patientEmail;
		  		newUser.phoneNumber= updateForm.get().patientPhone;
		  		newUser.provider="dummy";
		  		newUser.userid= updateForm.get().patientEmail;
		  		
		  		if(patientDetails == null || patientDetails.id ==0){
			  		newUser.save();
			  		patientDetails = User.authenticate("dummy",updateForm.get().patientEmail);
			  		isNewUser= true;
		  		}else{
		  			newUser.id= patientDetails.id;
		  			newUser.update();
		  		}
		  		apt.patient.id =patientDetails.id; 
		  	}
		  	apt.save();
		  	MailerScheduler.referredPatient(apt, user, isNewUser);
			//String[] appment = {"appment@gmail.com"};
			//MailerScheduler.scheduleMail(appment, "Urgent: Appointment requested by " + user.name, "Hi,<br> My client Id is "+user.clientId+ " want an appointment on "+ updateForm.get().date + " at "+updateForm.get().requesttime+ ".<br>"+updateForm.get().comments+ "<br>This request is due to personal urgency. Kindly accomodate.<br>Thanks,<br>"+user.name);
		    return ok();
		  }
		
		@SecureSocial.Secured
		public static Result startVideoSession(Long id) {
			SocialUser sUser = SecureSocial.currentUser();
	    	User user = User.authenticate(sUser.id.provider,sUser.id.id);  
		  	AppointmentHistory appointment = AppointmentHistory.getAppointmentDetails(id);
		  	if("D".equals(user.userType)){
			  	if(null == appointment.sessionId){
				  	try {
						  OpenTokSDK sdk = new OpenTokSDK(23104692, "2d8528251e19b0743d9dc27db12bc13703725658");
					        SessionProperties sp = new SessionProperties();
					        sp.p2p_preference = "enabled";
					        String sessionId = sdk.create_session(null, sp).getSessionId();
					        String token = sdk.generate_token(sessionId);
							appointment.sessionId = sessionId;
							appointment.tokenId = token;
							appointment.update();

					} catch (Exception e) {
						e.printStackTrace();
					}
			  	}else{
				  	try {
						  OpenTokSDK sdk = new OpenTokSDK(23104692, "2d8528251e19b0743d9dc27db12bc13703725658");
					        SessionProperties sp = new SessionProperties();
					        sp.p2p_preference = "enabled";
					        String token = sdk.generate_token(appointment.sessionId);
							appointment.tokenId = token;
							appointment.update();

					} catch (Exception e) {
						e.printStackTrace();
					}
			  		
			  	}
		  	}
			return ok(toJson(appointment));

		  }
		
		
		public static int checkDay(String day)
	    {
	        Map<String,Integer> mp=new HashMap<String,Integer>();
	        
	        mp.put("Sun",1);
	        mp.put("Mon",2);
	        mp.put("Tue",3);
	        mp.put("Wed",4);
	        mp.put("Thu",5);
	        mp.put("Fri",6);
	        mp.put("Sat",7);
	        
	        return mp.get(day).intValue();
	    }


		public static class UpdateAppointment {

			public long id;
			public String dateOfAppointment;
			public String appointmentTime;
			public String appointmentDuration = "00:30";
			public String appointmentHeadline;
			public String appointmentConfirmation;
			public String appointmentComment;
			public String created = null;
			public String appointmentEndTime = null;
			public String paymentStatus;
			public Double amountPaid;
			public String doctorComments;
			public String attended;
			public String video;
			public String sessionId;
			public String tokenId;
		}

		@SecureSocial.Secured
		public static Result getDoctorsHospitals() {
		  	SocialUser sUser = SecureSocial.currentUser();
		  	User user = User.authenticate(sUser.id.provider,sUser.id.id);
        	List<DoctorHospital> hospitalDetailsOfDoctor = DoctorHospital.getHospitalsForDoctor(user.id);
        	return ok(toJson(hospitalDetailsOfDoctor));
		}
		
		@SecureSocial.Secured
		public static Result doctorsreferralTemplates(Long id) {
        	List<DoctorsReferralTemplates> templates = DoctorsReferralTemplates.getDoctorsTemplates(id);
        	return ok(toJson(templates));
		}
		
		@SecureSocial.Secured
		public static Result getDoctorHospitals(Long id) {
        	List<DoctorHospital> hospitalDetailsOfDoctor = DoctorHospital.getHospitalsForDoctor(id);
        	return ok(toJson(hospitalDetailsOfDoctor));
		}
		@SecureSocial.Secured
		public static Result updateAppointment() {
			try{
				Form<UpdateAppointment> updateForm = form(UpdateAppointment.class).bindFromRequest();
			  	SocialUser sUser = SecureSocial.currentUser();
			  	User user = User.authenticate(sUser.id.provider,sUser.id.id);
			  	AppointmentHistory appointmentHistory = new AppointmentHistory();
			  	appointmentHistory.id=updateForm.get().id;
			  	appointmentHistory.paymentStatus="null".equals(updateForm.get().paymentStatus)?null:updateForm.get().paymentStatus;
			  	appointmentHistory.appointmentConfirmation="null".equals(updateForm.get().appointmentConfirmation)?null:updateForm.get().appointmentConfirmation;
			  	appointmentHistory.update();
			  	if("Y".equals(updateForm.get().appointmentConfirmation)){
				    AppointmentHistory app = AppointmentHistory.getAppointmentDetails(updateForm.get().id);
			  		User duser = User.getUserDetails(app.patient.id);
				  	SimpleDateFormat df = new SimpleDateFormat("MMM d, yyyy hh:mm:ss aaa");
				  	Date d = df.parse(updateForm.get().dateOfAppointment); 
				    DateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yyyy");
				  	MailerScheduler.sendGCMNotification(app,duser,"Your appointment on "+dateFormat.format(d) + " is confirmed by doctor.");		  	
			  	}else if("N".equals(updateForm.get().appointmentConfirmation)){
				    AppointmentHistory app = AppointmentHistory.getAppointmentDetails(updateForm.get().id);
			  		User duser = User.getUserDetails(app.patient.id);
				  	SimpleDateFormat df = new SimpleDateFormat("MMM d, yyyy hh:mm:ss aaa");
				  	Date d = df.parse(updateForm.get().dateOfAppointment); 
				    DateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yyyy");
				  	MailerScheduler.sendGCMNotification(app,duser,"Your appointment on "+dateFormat.format(d) + " is cancelled by doctor.");		  	
		  		
			  	}
				
			}catch(Exception ex){
		    	ex.printStackTrace();
		    }
		    return ok();
		  }	
		
}
